package com.wjc.basemodule.widget

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.MutableLiveData
import com.wjc.basemodule.R


/**
 * ClassName: com.hawatalk.live.ui.widget
 * Description: 弹窗管理
 * JcChen on 2020.11.30.8:41 PM
 */
class DialogManager(private val mContext: Context) {

  var mBuilder: AlertDialog.Builder = AlertDialog.Builder(mContext, R.style.LoadingDialogStyle)
  var mDialog: Dialog

  init {
    mDialog = mBuilder.create()
  }

  fun showProgressDialog(coverUrl: String?) {
    if (mDialog.isShowing) {
      mDialog.hide()
    }

    mDialog.setCancelable(true)
    mDialog.setCanceledOnTouchOutside(false)
    try {
      mDialog.show()
    } catch (e: java.lang.Exception) {
      e.printStackTrace()
    }
    val window = mDialog.window
    window!!.setBackgroundDrawable(ColorDrawable(-0x00000000)) //设置透明
    window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    window.setGravity(Gravity.CENTER)
    mDialog.setContentView(R.layout.layout_dialog_progress_dialog)
    val loadingTip = window.findViewById<TextView>(R.id.tv_dialog_loading_tip)

  }

  fun setAddTextChangedListener(etv: EditText, num: MutableLiveData<String>, totalNum: Int) {
    etv.addTextChangedListener(object : TextWatcher {
      override fun afterTextChanged(s: Editable?) {
        num.value = "${s?.length ?: 0}/$totalNum"
      }

      override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
      }

      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
      }
    })
  }

  val TAG = "DialogManager"
  fun dismissDialog() {
    if (mDialog.window != null) {
      if (mContext is Activity && !mContext.isFinishing) {
        try {
          mDialog.dismiss()
        } catch (e: java.lang.Exception) {
          e.printStackTrace()
        }
      } else {
        dismissTryCrash()
      }
    }
  }

  private fun dismissTryCrash() {
    try {
      mDialog.dismiss()
    } catch (e: java.lang.Exception) {
      e.printStackTrace()
    }
  }

  interface DialogListener {
    fun okClick(msg: String)
    fun cancelClick() {

    }
  }

}